package com.mwm.paiwei.meiye.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.lianjiao.core.activity.BaseActivity;
import com.lianjiao.core.net.BaseListener;
import com.lianjiao.core.net.HttpUtil;
import com.lianjiao.core.net.RequestParams;
import com.lianjiao.core.utils.LsToast;
import com.lianjiao.core.utils.StringUtil;
import com.lianjiao.core.widget.EditTextClear;
import com.mwm.paiwei.meiye.AESUtils;
import com.mwm.paiwei.meiye.config.MeiYeConfig;
import com.mwm.paiwei.meiye.model.LoginBean;
import com.mwm.paiwei.meiye.util.ZipUtil;
import com.mwm.paiwei.meiye.R;
import com.mwm.paiwei.meiye.util.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;

import roboguice.inject.InjectView;

/**
 * Created by wujamie on 17/3/1.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @InjectView(R.id.etLoginPhone)
    private EditTextClear etLoginPhone;
    @InjectView(R.id.etLoginPassword)
    private EditTextClear etLoginPassword;
    @InjectView(R.id.btnLoginSubmit)
    private Button btnLoginSubmit;

    private boolean isLoadNextActivity = false;

    SharedPreferences preferences = null;

    private TextWatcher inputTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (StringUtil.isEmpty(etLoginPhone.getText().toString()) || StringUtil.isEmpty(etLoginPassword.getText().toString())) {
                btnLoginSubmit.setEnabled(false);
            } else {
                btnLoginSubmit.setEnabled(true);
            }
        }
    };
    private LoginBean loginBean;
    private Boolean isFromOut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        isLoadNextActivity = getIntent().getBooleanExtra("isLoadNextActivity", false);

        isFromOut = getIntent().getBooleanExtra("isFromOut", false);

        preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        String username = preferences.getString("username", "");
        etLoginPhone.setText(username);
        String password = preferences.getString("password", "");

        //TODO:多了個判斷 是用戶點擊退出操作时，才不修改MeiYeConfig.JS_VERSION
        if (!isFromOut) {
            MeiYeConfig.JS_VERSION = preferences.getFloat("js_version", -1);
        }

        MeiYeConfig.JS_DOWNLOAD_URL = preferences.getString("js_download_url", "");

        password = AESUtils.decrypt(username, password);
        etLoginPassword.setText(password);
        if (username != null && password != null) {
            btnLoginSubmit.setEnabled(true);
            onClick(btnLoginSubmit);
        }
        if (Util.isFileExit(MeiYeConfig.FILE_PATH + "/index.zip")) {
        } else {
        }

        initEdit();
    }

    @Override
    protected void onResume() {
        super.onResume();

        String username = preferences.getString("username", "");
        etLoginPhone.setText(username);
        String password = preferences.getString("password", "");
        password = AESUtils.decrypt(username, password);
        etLoginPassword.setText(password);
        if (username != null && password != null) {
            btnLoginSubmit.setEnabled(true);
        } else {
            btnLoginSubmit.setEnabled(false);
        }
    }

    private void initEdit() {
        etLoginPhone.addTextChangedListener(inputTextWatcher);

        etLoginPassword.addTextChangedListener(inputTextWatcher);
    }

    /*

    18516587980
    aaaaaa
    这个帐号对应一个角色

    13512111911
    aaaaaa
    这个帐号对应2个角色
     */

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLoginSubmit:
                if (StringUtil.isEmpty(etLoginPhone.getText().toString())) {
                    LsToast.show(mContext, "用户名不能为空");
                    return;
                }

                if (StringUtil.isEmpty(etLoginPhone.getText().toString())) {
                    LsToast.show(mContext, "密码不能为空");
                    return;
                }
//                long uid_new = preferences.getLong("uid_new", -1);
//                String token_new = preferences.getString("token_new", "");
//                String utype_new = preferences.getString("utype_new", "");
//                Log.e("hello111222", uid_new + "..." + token_new + "..." + utype_new);
//                if (uid_new != -1 && !TextUtils.isEmpty(token_new) && !TextUtils.isEmpty(utype_new)) {
//
//                    try {
//                        ZipUtil.upZipFile(MeiYeConfig.FILE_PATH + "/index.zip", MeiYeConfig.local_url);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    Intent i = new Intent(LoginActivity.this, WebViewActivity.class);
////
//                    Bundle bundle = new Bundle();
//                    bundle.putLong("uid", uid_new);
//                    bundle.putString("token", token_new);
//                    bundle.putString("utype", utype_new);
////                    bundle.putBoolean("isLoadNextActivity", isLoadNextActivity);
//                    i.putExtras(bundle);
//
//                    startActivity(i);
//                    finish();
//                } else {
//                    Log.e("hello222", "here");
                    goNetW();
//                }
        }
    }

    private void goNetW() {
        showProgressDialog();
//                String url = MeiYeConfig.url + "Api/Auth/Token";
        String url = MeiYeConfig.url + "Api/Auth/TokenByMultiUser";
        RequestParams params = new RequestParams();
        params.put("userName", etLoginPhone.getText().toString().trim());// 注意：
        params.put("userPwd", etLoginPassword.getText().toString().trim());// 注意：
        HttpUtil.post(params, url, new BaseListener() {

            @Override
            public void onError(String err) {
                closeProgressDialog();
                JSONObject json = null;
                try {
                    json = new JSONObject(err);
                    LsToast.show(mContext, json.getString("msg"));
                } catch (JSONException e) {
                    LsToast.show(mContext, "访问异常");
                }
            }

            @Override
            public void onComplete(String context) {
                Log.e("hello", context + "...");
                closeProgressDialog();
                try {
                    loginBean = new Gson().fromJson(context, LoginBean.class);
                    if (loginBean.getResult() == 0) {
                        LsToast.show(mContext, loginBean.getMsg());
                        return;
                    }

                    String userName = etLoginPhone.getText().toString().trim();
                    String userPassword = etLoginPassword.getText().toString().trim();
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("username", userName);
                    editor.putString("password", AESUtils.encrypt(userName, userPassword));
                    editor.commit();
                    ZipUtil.upZipFile(MeiYeConfig.FILE_PATH + "/index.zip", MeiYeConfig.local_url);

                    if (loginBean.getData().getUserCount() == 1) {

                        SharedPreferences.Editor editorNew = mContext.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
                        editorNew.putLong("uid_new", loginBean.getData().getUserTokens().get(0).getUserId());
                        editorNew.putString("token_new", loginBean.getData().getUserTokens().get(0).getToken());
                        editorNew.putString("utype_new", loginBean.getData().getUserTokens().get(0).getUserType() + "");
                        editorNew.commit();

                        Intent i = new Intent(LoginActivity.this, WebViewActivity.class);
//
                        Bundle bundle = new Bundle();
                        bundle.putLong("uid", loginBean.getData().getUserTokens().get(0).getUserId());
                        bundle.putString("token", loginBean.getData().getUserTokens().get(0).getToken());
                        bundle.putString("utype", loginBean.getData().getUserTokens().get(0).getUserType() + "");
//                    bundle.putBoolean("isLoadNextActivity", isLoadNextActivity);
                        i.putExtras(bundle);

                        startActivity(i);
                        finish();
                    } else {
                        Intent goIntent = new Intent(LoginActivity.this, CharactorSelectActivity.class);
                        goIntent.putExtra("loginBean", loginBean);
                        startActivity(goIntent);
                        finish();
                    }
                }
                //TODO:新增登陆是的检测，要是包受损或没有安装好则跳回loading界面重新下载
                catch (FileNotFoundException e1){
                    Log.e("hello333", e1.toString());
                    e1.printStackTrace();
                    Intent intent = new Intent(LoginActivity.this, LoadingActivity.class);
                    intent.putExtra("isQzUpdate",true);
                    startActivity(intent);
                    finish();
                }
                catch (Exception e) {
                    Log.e("hello6666", e.toString());
                    e.printStackTrace();
                }


//                        JSONObject json = null;
//                        try {
//                            json = new JSONObject(context);
//
//                            if (json.getString("result").equals("0")) {
//                                LsToast.show(mContext, json.getString("msg"));
//                                return;
//                            }
//
//                            String userName = etLoginPhone.getText().toString().trim();
//                            String userPassword = etLoginPassword.getText().toString().trim();
//                            long userId = json.getJSONObject("data").getLong("userId");
//                            String userToken = json.getJSONObject("data").getString("token");
//                            String userType = json.getJSONObject("data").getString("userType");
//
//                            SharedPreferences.Editor editor = preferences.edit();
//                            editor.putString("username", userName);
//                            editor.putString("password", AESUtils.encrypt(userName, userPassword));
//                            editor.commit();
//
//                MeiYeConfig.USERID = userId;
//                User user = new User();
//                user.setUserid(userId);
//                user.setUsername(userName);
//                user.setPassword(userPassword);
//                user.setToken(userToken);
//                user.setUserType(userType);
//                user.setCreatedTime(new Date().toString());
//                MeiYeConfig.user = user;
//                            try {
//                                ZipUtil.upZipFile(MeiYeConfig.FILE_PATH + "/index.zip", MeiYeConfig.local_url);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                                return;
//                            }
//
//                            Intent i = new Intent(LoginActivity.this, WebViewActivity.class);
//
//                            Bundle bundle = new Bundle();
//                            bundle.putLong("uid", userId);
//                            bundle.putString("token", userToken);
//                            bundle.putString("utype", userType);
//                            bundle.putBoolean("isLoadNextActivity", isLoadNextActivity);
//                            i.putExtras(bundle);
//
//                            startActivity(i);
//                            finish();
//                        } catch (JSONException e) {
//                            LsToast.show(mContext, "数据异常");
//                        }
            }
        });
    }


}
